const service = require('../services')
const utils = require('../utils')
const errcode = require('../utils/errcode')

exports.login = async ctx => {
    const username = ctx.request.body.username
    const password = ctx.request.body.password

    if (!username || !password) return ctx.error(errcode.REQUIRED_PARAMS)

    const code = await service.user.login(username, password)

    if (code === -1 || code === 0) return ctx.error(errcode.USER_NOT_EXISTS)
    if (code === -2) return ctx.error(errcode.DISABLE_USER)
    if (code === -3) return ctx.error(errcode.PASSWORD_NOMATCH)

    const user = await service.user.getLoginInfo(code)

    // 设置session
    ctx.session.user = {
        id: user.id,
        username: user.username,
        nickname: user.nickname
    }
    ctx.session.loginAt = Date.now()

    user.loginAt = ctx.session.loginAt
    ctx.success(user)
}

exports.logout = async ctx => {
    ctx.session.user = null
    ctx.session.loginAt = null
    ctx.success()
}
